package com.gyms.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVCardBean;
import com.classic.okhttp.beans.HVClickInfoBean;
import com.classic.okhttp.beans.HVMyOrderInfoBean;
import com.classic.okhttp.beans.HVOrderCardBean;
import com.classic.okhttp.beans.HVProductOrderFieldBean;
import com.classic.okhttp.beans.HVRefundConfigBean;
import com.classic.okhttp.beans.HVShareActivityBean;
import com.classic.okhttp.beans.HVSignBean;
import com.classic.okhttp.beans.HVVenueOrderFieldBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IOrderService;
import com.classic.okhttp.services.IPayService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.BannerIntentManger;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.CouponManger;
import com.gyms.manager.DataCenter;
import com.gyms.manager.OrderManger;
import com.gyms.manager.PayDialogManager;
import com.gyms.manager.RevertManger;
import com.gyms.manager.StateUtils;
import com.gyms.manager.StatisticsManager;
import com.gyms.manager.TitleManager;
import com.gyms.pay.PayResult;
import com.gyms.view.bottomview.PaymentDialog;
import com.gyms.view.bottomview.RefundDialog;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import utils.ActivityUtils;
import utils.DateUtil;
import utils.DecimalUtils;
import utils.StringUtils;
import weight.ComDialog;
import weight.UiEvent;

import static com.gyms.R.id.rl_card;
import static utils.DateUtil.getSimpleDate;

/**
 * 订单详情
 * ltx
 */

public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_lave_time)//剩余时间
    TextView mTvLaveTime;
    @BindView(R.id.tv_order_price)
    TextView mTvOrderPrice;//总价格
    @BindView(R.id.tv_order_gym_name)
    TextView mTvOrderGymName;
    @BindView(R.id.tv_code)//验证码
    TextView mTvCodeStr;
    @BindView(R.id.tv_create_time)//创建时间
    TextView mTvCreateTime;
    @BindView(R.id.tv_project_name)//运动项目名称
    TextView mTvProjectName;
    @BindView(R.id.ll_true_pay)//确认支付
    LinearLayout mLlTruePay;
    @BindView(R.id.ll_order_detail_add)//添加子的场馆列表的LinearLayout
    LinearLayout mLlOrderDetailAdd;
    @BindView(R.id.tv_confirm_discount)
    TextView mTvConfirmDiscount;
    @BindView(R.id.ll_order_number)
    LinearLayout mLlOrderNumber;//订单号
    @BindView(R.id.tv_actual_price)
    TextView mTvActualPrice;//实付价格
    @BindView(R.id.rl_code)
    RelativeLayout mRlCode;//支付条形码
    @BindView(R.id.rl_card)
    RelativeLayout mRlCard;//卡券
    @BindView(R.id.tv_order_id)
    TextView mTvOrderId;//订单号
    @BindView(R.id.tv_pay_way)
    TextView mTvPayWay;//支付方式
    @BindView(R.id.tv_card)
    TextView mTvCardName;//卡卷名
    @BindView(R.id.tv_count)
    TextView mTvCount;//合计或者实付
    @BindView(R.id.iv_code)
    ImageView mIvCode;//二维码图片
    private String mOrderId = "";
    private long mLeaveTime = -1;
    private double mAllPrice;//总共价格
    private double discountedPrice;//实付价格
    private boolean isOverTime;//是否超时
    private PayDialogManager dialogManager;//成功或者失败后的页面
    //确认支付
    private boolean isConfirmOrder;//从预定场地进入是预定

    public boolean isProduct;//是产品订单
    private boolean isFromMyOrder;//从我的订单进去
    private boolean isFromProduct;//从产品详情进入
    private boolean isFromGym;//从场馆进入
    private String strFromProduct;//从产品进入的string标识
    private String strFromGym;//从场馆进入的string标识
    private boolean isPayWithCar;//支付是否使用优惠劵


    //右边的按钮
    private TextView mRightView;//右边的按钮

    private boolean mIsPay;

    public ArrayList<HVVenueOrderFieldBean> orderField;//子订单列表

    private Handler mHandler = new Handler();

    private RefundDialog mRefundDia;

    //订单类型 (1场馆  2产品)
    private final static int GYM = 1;
    private final static int PRODUCT = 2;

    private static final int SDK_PAY_FLAG = 200;//支付宝回调
    private static final int COUBTDOWN = 101;//倒计时回调

    private boolean mNopay;//是否未支付

    private String payInfo;//传给支付宝的订单信息

    private HVMyOrderInfoBean mHVMyOrderInfoBean;//订单详情

    //优惠卷减的减额
    private double discount;
    private HVCardBean mHVCardBean;//我的卡卷类
    //优惠券id
    private Integer mSelctedCouponId;
    private String mBarCode;//验证码
    private String mCouponName;//卡卷名
    private boolean isBackGround;//是否进入后台过
    private boolean isNeedReq;//是否需要重新请求
    private boolean isRemain;//是否正在倒计时

    private boolean ihaveCard=false;
    //是否已经完成
    private boolean isUsed;//是否已经完成
    //支付方式
    private boolean isZfbPay=true;//默认是支付宝
    //微信支付相关
    private IWXAPI mIWXAPI;

    //应用ID  //(String)
    private String appid;

    //商户号  //(String)
    private String partnerid;

    //预支付交易会话ID  //(String)
    private String prepayid;

    //扩展字段 package为java关键字,改用packageStr  //(String)
    private String packageStr;

    //随机字符串  //(String)
    private String noncestr;

    //时间戳  //(String)
    private String timestamp;

    //签名,支付宝只有这个参数用值  //(String)
    private String sign;
    private String mWxAppId="wx7d8e0d35db4505dd";
    private String mGymId="";
    //订单类型
    private int mOrderType;	//0 无,1 场地 2产品

    //更改订单样式相关
    @BindView(R.id.rl_detail_actual_pay)
    RelativeLayout mRlDetailActualPrice;
    @BindView(R.id.tv_deatil_actual_price)
    TextView mTvDetailActualPrice;
    @BindView(R.id.view_detail_pay_actual)
    View mViewDetailActualPrice;
    @BindView(R.id.iv_discount_go)
    ImageView mIvDiscountGo;
    //退款金额
    private Integer mRefundAmount;
    private Integer mAvailableCouponCount;//可用卡卷数量

    public RevertManger mRevertManger;//退款规则
    public ArrayList<HVRefundConfigBean> mRefundConfigs;
    @BindView(R.id.tv_revert_rule)
    TextView mTvRevertRule; //退款说明
    @BindView(R.id.iv_revert_icon)
    ImageView mIvRevertIcon;//问号图标
    private boolean isCanRefund;//服务器传来的是否可退

    private boolean isCanGoRevertDetail;//退款规则是否可点击

    private ArrayList<Integer> mAvailableCouponList;//符合该订单的卡卷Id

    private CouponManger mCouponManger;

    //立即前往
    @BindView(R.id.ll_forward)
    LinearLayout mLlForward;
    @BindView(R.id.view_card_line)
    View mViewCardLine;//卡卷的下划线

    private HVClickInfoBean mForwardDetail;//立即前往点击类
    private BannerIntentManger mBannerIntentManger;//立即前往点击

    //邀请有礼
    @BindView(R.id.tv_invitation)
    TextView mTvInvitation;//邀请有礼
     @BindView(R.id.ll_share_invitation)
    LinearLayout mLlShareInvitation;
    private DataCenter mDataCenter;
    private HVShareActivityBean mHVShareActivityBean;

    private MyHandler mHandlder =new MyHandler(this);

    //解决handler 内存泄漏
    private static class MyHandler extends Handler {
        private final WeakReference<OrderDetailActivity> mActivity;

        public MyHandler(OrderDetailActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            OrderDetailActivity activity = mActivity.get();
            if(activity==null){
                return;
            }
            switch (msg.what) {
                case COUBTDOWN://倒计时
                    if (activity.mLeaveTime > 0) {
                        activity.mLeaveTime -= 1;
                    }
                    StringUtils.updateTextView(activity.mLeaveTime, activity.mTvLaveTime);
                    if (null != activity.dialogManager) {
                        StringUtils.updateTextView(activity.mLeaveTime, activity.dialogManager.tvTimecount);
                    }
                    activity.isOverTime = activity.mTvLaveTime.getText().toString().equals(activity.getResources().getString(R.string.str_over_time));
                    if (activity.isOverTime) {//已经超时就不循环
                        activity.doShowOverDialog();
                        return;
                    }
                    activity.mHandlder.sendEmptyMessageDelayed(COUBTDOWN, 1000);
                    break;
                case SDK_PAY_FLAG://支付宝回调
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */

                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        activity.tradeQuery();

                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(activity, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                            activity.doPayFail();

                        }
                    }

                    break;

            }
        }
    }


    /**
     * 查询订单页面
     */

    private void tradeQuery() {
        loadingView.show();
        IPayService.tradeQuery(this, mOrderId, isZfbPay?Enum.EnumPayWay.Alipay:Enum.EnumPayWay.Wechatpay, false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {
                if(isFromGym){
                    EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_GYM_PAY_SUC,null));
                }
                doPaySuccess();
                dialogDis();
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                doPaySuccess();
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                doPaySuccess();
                dialogDis();
            }
        });
    }

    /**
     * 支付失败
     */

    private void doPayFail() {
        dialogManager = new PayDialogManager(OrderDetailActivity.this);
        //防止activity销毁后调用弹出框
        if (!OrderDetailActivity.this.isFinishing()) {
            dialogManager.showPayFailed();
        }
        dialogManager.setPayResultListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              /*  if (isZfbPay) {
                    doPay();
                } else {
                    doWeiXinPay();
                }*/
                chosePayWay();
                dialogManager.dismissDialog();
            }
        });
        dialogManager.setPaySuccessCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogManager.dismissDialog();
            }
        });
    }

    /**
     * 支付成功
     */

    private void doPaySuccess() {
        if (isFromMyOrder) {//如果从我的订单页面进去 返回刷新列表
            EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_REFRESH_MY_ORDER, null));
        }
        isConfirmOrder = false;
        mHandlder.removeCallbacksAndMessages(null);//倒计时停止
        dialogManager = new PayDialogManager(OrderDetailActivity.this);
        //防止activity销毁后调用弹出框
        if (!OrderDetailActivity.this.isFinishing()) {
            dialogManager.showPaySuccess();
        }
        dialogManager.setPayResultListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTitleManager.setTitle("订单详情");
                getVenueOrderInfo();
                dialogManager.dismissDialog();
            }
        });
        dialogManager.setPaySuccessCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTitleManager.setTitle("订单详情");
                getVenueOrderInfo();
                dialogManager.dismissDialog();
            }
        });
    }


    /**
     * 超时时弹出框 跳出页面
     */
    private void doShowOverDialog() {
        final ComDialog dialog = CommonDialogUtils.dialog(OrderDetailActivity.this,getSupportFragmentManager(),getString(R.string.str_order_remind),"支付超时");
        dialog.setCancelGone();
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//三种情况  从预定座位进入  从产品进入  从我的订单进入
                dialog.dismiss();
                if (isConfirmOrder) {//从预定座位或者产品 进入 确认订单
//                    if (isFromProduct) {//从产品进去直接返回
                        onBackPressed();
//                    } else
//                        startActivity(GymDetailActivity.class, true);
                } else {
//                    startActivity(MyOrderActivity.class, true);
                    onBackPressed();
                    //刷新列表
                    EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_REFRESH_MY_ORDER, null));
                }
            }
        });
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mDataCenter=DataCenter.getInstance();
        mHVShareActivityBean=mDataCenter.getHVShareActivityBean();
        Bundle mBundle = getIntent().getExtras();
        mCouponManger=CouponManger.getInstance();
        if (null != mBundle) {
            mOrderId = mBundle.getString(Constants.FLAG_INTENT_GYM_ORDER_ID, "");
            String mFlagIsConfirm = mBundle.getString(Constants.FLAG_INTENT_IS_CONFIRM, "");//标识是不是订单确认订单
            String mFlagMyOrder = mBundle.getString(Constants.FALG_INTENT_MY_ORDER, "");//标识是不是从我的订单进入
            int mProductTag = mBundle.getInt(Constants.FALG_INTENT_PRODUCT_TAG, -1);//是否是产品订单
            strFromProduct = mBundle.getString(Constants.FALG_INTENT_FROM_PRODUCT, "");//标识是从产品详情进入
            strFromGym = mBundle.getString(Constants.FALG_INTENT_FROM_GYM, "");//标识是从场馆预定进入
            mOrderType=mBundle.getInt(Constants.FLAG_INTENT_UNPAY_TYPE,-1);
            isConfirmOrder = !StringUtils.isNull(mFlagIsConfirm);
            isProduct = mProductTag == Constants.PRODUCT_ORDER_TYPE;//1为场馆订单 2为场次订单
            isFromMyOrder = mFlagMyOrder.equals(Constants.FALG_INTENT_MY_ORDER);
            isFromProduct = strFromProduct.equals(Constants.FALG_INTENT_FROM_PRODUCT);
            isFromGym = strFromGym.equals(Constants.FALG_INTENT_FROM_GYM);
        }
        createLoadingView(getString(R.string.str_loading), true);
        mRightView = mTitleManager.getmRightTV();
        mRightView.setVisibility(View.VISIBLE);
        mRightView.setOnClickListener(this);
        setTitle(isConfirmOrder ? getString(R.string.str_confirm_order) : getString(R.string.str_order_detail));
        setOrderBack();
        setTitleTheme();
        mIWXAPI = WXAPIFactory.createWXAPI(getApplicationContext(), null);

        // 将该app注册到微信


        mIWXAPI.registerApp(Constants.App_Id);
        //初始化 退款管理类
        mRevertManger =RevertManger.getInstance();
    }

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected void setListener() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mBatInfoReceiver, filter);
        mRlCode.setOnClickListener(this);
    }

    @Override
    protected void processLogic() {
        getVenueOrderInfo();
    }

    /**
     * 获取订单详情
     */
    private void getVenueOrderInfo() {
        loadingView.show();
        IOrderService.getOrderInfo(this, isProduct ? Enum.EnumCollect.Product : Enum.EnumCollect.Venue, mOrderId, false, new ObjectCallback<HVMyOrderInfoBean>() {
            @Override
            public void onSuccess(HVMyOrderInfoBean response, String message) {
                if (null != response) {
                    mHVMyOrderInfoBean = response;
                    doFullView(response);
                }
                dialogDis();
            }

            @Override
            public void onErrorT(int code, HVMyOrderInfoBean response, String errorMessage) {
                ToastUtil.showToast(mContext, errorMessage);
                dialogDis();
                mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
                isRemain=false;
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
                mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
                isRemain=false;
            }
        });
    }

    /**
     * 订单详情
     *
     * @param mHVMyOrderInfoBean 订单详情的bean
     */
    private void doFullView(HVMyOrderInfoBean mHVMyOrderInfoBean) {
        //可用优惠券相关
        mAvailableCouponList=mHVMyOrderInfoBean.availableCouponList;
        //订单状态
        int orderStaus = mHVMyOrderInfoBean.getOrderState().value;
        mGymId=mHVMyOrderInfoBean.getVenueId();//场馆Id
        String mOrderStaus = OrderManger.getOrderStatus(orderStaus);
        mNopay = mHVMyOrderInfoBean.getOrderState() == Enum.EnumOrderState.Nopay;
        mBarCode = mHVMyOrderInfoBean.getBarCode();//验证码
        mTvCodeStr.setText(StringUtils.stringAddSpace(mBarCode));
        mLeaveTime = mHVMyOrderInfoBean.getPayOverTime();
        mTvOrderGymName.setText(mHVMyOrderInfoBean.getVenueName());
        mTvProjectName.setText(mHVMyOrderInfoBean.getProjectName());
        mIsPay = mHVMyOrderInfoBean.getOrderState() == Enum.EnumOrderState.Paid;



        if (!mNopay) {//不是未支付的情况下
            mTvLaveTime.setText(mOrderStaus);
//            mLlOrderNumber.setVisibility(View.VISIBLE);
            mIvDiscountGo.setVisibility(View.GONE);
        }else{
//            mLlOrderNumber.setVisibility(View.GONE);
            mIvDiscountGo.setVisibility(View.VISIBLE);
        }
        if (mIsPay) {//已支付
            mLlTruePay.setVisibility(View.GONE);
//            mRlCode.setVisibility(View.VISIBLE);
//            mRlCard.setVisibility(View.VISIBLE);

//            mTvCount.setText("实付");
        } else {
            mLlTruePay.setVisibility(View.VISIBLE);
//            mRlCode.setVisibility(View.GONE);
//            mRlCard.setVisibility(View.VISIBLE);
//            mTvCount.setText("合计");
        }
        if (mNopay) {//如果未支付
            if (!isRemain) {//还没倒计时过
                mHandlder.sendEmptyMessageDelayed(COUBTDOWN, 1000);//开始循环
                isRemain = true;
            }
            if (isConfirmOrder) {//确认订单 不需要取消订单
                mRightView.setVisibility(View.GONE);
                mLlOrderNumber.setVisibility(View.GONE);
            }else{
                mLlOrderNumber.setVisibility(View.VISIBLE);

            }
            mRlDetailActualPrice.setVisibility(View.GONE);
            mViewDetailActualPrice.setVisibility(View.GONE);

        } else {
            mLlTruePay.setVisibility(View.GONE);
            mRightView.setVisibility(View.VISIBLE);
            mRlDetailActualPrice.setVisibility(View.VISIBLE);
            mViewDetailActualPrice.setVisibility(View.VISIBLE);
            mLlOrderNumber.setVisibility(View.VISIBLE);
        }
        orderField = mHVMyOrderInfoBean.getOrderField();//子订单列表
        HVProductOrderFieldBean orderProduct = mHVMyOrderInfoBean.getOrderProduct();//产品订单
        int orderType = mHVMyOrderInfoBean.getOrderType().value;//订单类型
        mLlOrderDetailAdd.removeAllViews();

        isCanRefund=mHVMyOrderInfoBean.getCanRefund();
        if (mIsPay) {//在支付的情况下
            mRightView.setVisibility( isCanRefund? View.VISIBLE : View.GONE);//是否可以退款
        }
        mRightView.setText(mIsPay ? "退款" : "取消订单");//已支付
        mTvCreateTime.setText(String.format(getResources().getString(R.string.str_order_create_time), getSimpleDate(mHVMyOrderInfoBean.getCreateTime())));
        mTvOrderId.setText(String.format(getResources().getString(R.string.str_order_id), mHVMyOrderInfoBean.getOrderId()));
        mTvPayWay.setText(String.format(getResources().getString(R.string.str_pay_way), OrderManger.getPayWay(mHVMyOrderInfoBean.getPayWay().value)));
//        mTvPayWay.setVisibility(mIsPay ? View.VISIBLE : View.GONE);
//        OrderManger.doShowOrderStatue(orderStaus,mTvPayWay);
        //我的卡卷
        mAllPrice=mHVMyOrderInfoBean.getActualPrice();//总金额 未减折扣
        HVOrderCardBean mHVOrderCardBean = mHVMyOrderInfoBean.getCard();
        if (mIsPay && !StringUtils.isNull(mHVOrderCardBean)) {
            isPayWithCar = true;
        }

        discountedPrice = mAllPrice;
        if (!StringUtils.isNull(mHVOrderCardBean)) {
            ihaveCard=true;
            mCouponName = mHVOrderCardBean.getCouponName();
            mTvCardName.setText(mCouponName);//设置卡卷名
            discount = mHVOrderCardBean.getCouponMoney();//可减价格
            mSelctedCouponId = mHVOrderCardBean.getCouponUserId();
           /* if(discount>=mAllPrice){//当前卡卷的减额大于总额 设置为总额为0.01分
                discount=mAllPrice-0.01;
            }*/
            changePrice(true);//改变总价
        }
        if(isPayWithCar){
            double mRevertMonery=mRevertManger.doRevertAllChildOrders(orderField,discountedPrice,DateUtil.getCurTimeS());
            if(mRevertMonery==-1||mRevertMonery==0.0){
                mRightView.setVisibility(View.GONE);
            }/*else{
                mRightView.setVisibility(View.VISIBLE);
            }*/
        }
        doAddChildList(orderType, orderProduct);
        if(mNopay&&StringUtils.isNull(mHVOrderCardBean)){
            //未支付的情况下 显示优惠卷可用数量
            mAvailableCouponCount=mHVMyOrderInfoBean.getAvailableCouponCount();//可用卡卷数量
            OrderManger.setAvailableCouponCount(this,mAvailableCouponCount,mTvConfirmDiscount);
        }else if(!mNopay&&StringUtils.isNull(mHVOrderCardBean)){
            mTvConfirmDiscount.setText("无");
            mTvConfirmDiscount.setTextColor(getResources().getColor(R.color.c_999999));
        }
        //使用完之后的操作
        isUsed = mHVMyOrderInfoBean.getOrderState() == Enum.EnumOrderState.Used;//是否已经使用
        if(isUsed){//已使用变灰色
            mTvCodeStr.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            mTvCodeStr.setTextColor(getResources().getColor(R.color.c_999999));
            mIvCode.setImageResource(R.mipmap.icon_refund_press);

        } else {//没使用过颜色变亮
            mTvCodeStr.setTextColor(getResources().getColor(R.color.c_FF9D0A));
            mIvCode.setImageResource(R.mipmap.icon_refund_normal);
        }
        boolean mIsRefundOrComplete= OrderManger.isRefundOrComplete(orderStaus);//是否是正在退款中或者已经完成的状态
        if(mIsRefundOrComplete){//正在退款中 或者完成隐藏优惠劵
            mRightView.setVisibility(View.GONE);
//            mRlCard.setVisibility(View.VISIBLE);
//            mRlCode.setVisibility(View.VISIBLE);
        }
        doInitRevertData(mHVMyOrderInfoBean);
        doShowRevertTime(mTvRevertRule,mIvRevertIcon,isProduct);

        //条形码的更新
        boolean isForbiddenUseCoupon = mHVMyOrderInfoBean.forbiddenUseCoupon;//是否禁止使用优惠券（仅针对待付款）
        boolean isForbiddenBarCode = mHVMyOrderInfoBean.forbiddenBarCode;//是否禁止显示（仅正对已付款）自动核销类专用  //(boolean)
        OrderManger.doShowOrderStatue(orderStaus,mRlCode,mTvPayWay,mRlCard,mViewCardLine,isForbiddenUseCoupon,isForbiddenBarCode);

        //立即前往相关逻辑处理
        mForwardDetail =mHVMyOrderInfoBean.forwardDetail;
        String mForwardButtonText=mHVMyOrderInfoBean.forwardButtonText;
        OrderManger.doForward(orderStaus,mForwardDetail,mLlForward,mForwardButtonText);

        //分享有礼相关
       boolean isShareActivitying= StateUtils.isShareActivity(mHVShareActivityBean);
       boolean isShowOrderShare= StateUtils.isShowOrderShare(isShareActivitying,orderStaus);
       if(isShowOrderShare){
           mLlShareInvitation.setVisibility(View.VISIBLE);
           mTvInvitation.setText(mHVShareActivityBean.getText());
       }else {
           mLlShareInvitation.setVisibility(View.GONE);
       }

    }

    /**
     * 显示提前多少小时可退款
     * @param tvRevertRule View
     * @param ivRevertIcon
     */

    public void doShowRevertTime(TextView tvRevertRule, ImageView ivRevertIcon,boolean isProduct) {
        if(!isCanRefund){
            tvRevertRule.setText("不支持退款");
            ivRevertIcon.setVisibility(View.GONE);
            isCanGoRevertDetail=false;
        }else if(isProduct){//产品隐藏图标不可点击
            isCanGoRevertDetail=false;
            if(isCanRefund&&mIsPay){
                tvRevertRule.setText("支持退款");
            }
            ivRevertIcon.setVisibility(View.GONE);

        }else{//场馆订单
            if(StringUtils.isNull(mRefundConfigs)){
                tvRevertRule.setText("支持退款");
                ivRevertIcon.setVisibility(View.VISIBLE);
            }else{
                HVRefundConfigBean mConfigBean=mRefundConfigs.get(0);
                OrderManger.doShowRevertText(mConfigBean,tvRevertRule);
                ivRevertIcon.setVisibility(View.VISIBLE);
            }
            isCanGoRevertDetail=true;
        }
    }

    /**
     * 初始化 退款规则数据
     * @param mHVMyOrderInfoBean 订单详情bean
     */

    private void doInitRevertData(HVMyOrderInfoBean mHVMyOrderInfoBean) {
        int mServerTS=mHVMyOrderInfoBean.getServerTS();
        int mLocationTimeS=DateUtil.getCurTimeS();//获取成功后本地的时间
         mRefundConfigs=mHVMyOrderInfoBean.getRefundConfigs();
        mRevertManger.initDatas(mServerTS,mLocationTimeS,mRefundConfigs);

    }

    /**
     * 创建子的订单列表
     *
     * @param orderType    订单类型 1为场地 2为产品
     * @param orderProduct 产品订单
     */

    private void doAddChildList(int orderType, HVProductOrderFieldBean orderProduct) {
//        mAllPrice = 0;
        boolean isPayAndWithCard = mIsPay && isPayWithCar;
        if (GYM == orderType) {//场馆
            if (StringUtils.isNull(orderField)) {
                return;
            }
//            boolean isShowOrderDetail=isConfirmOrder || mNopay;
            List<Boolean> isRefundings = new ArrayList<>();//存放是否是退单中  如果子订单全都是退单中 那么大订单也变成退单中
            for (HVVenueOrderFieldBean mHVVenueOrderFieldBean : orderField) {
                int gymState = mHVVenueOrderFieldBean.getOrderState().value;//场地订单的状态
                boolean isRefunding = OrderManger.isRefunding(gymState);//是否退款中
                isRefundings.add(isRefunding);
                //如果是退款中就显示退款中的标签，字体显示999999否则显示333333
                View mOrderChildView = LayoutInflater.from(mContext).inflate(R.layout.order_confirm_item, null, false);//同一显示确认订单页面
                TextView mTvOrderSinglePrice = (TextView) mOrderChildView.findViewById(R.id.tv_order_single_price);
                TextView mTvOrderWeek = (TextView) mOrderChildView.findViewById(R.id.tv_order_week);
                TextView mTvOrderDate = (TextView) mOrderChildView.findViewById(R.id.tv_order_date);
                TextView mTvOrderTime = (TextView) mOrderChildView.findViewById(R.id.tv_order_time);
                ImageView mBacking = (ImageView) mOrderChildView.findViewById(R.id.iv_baking);
                TextView mTvOrderFieldName = (TextView) mOrderChildView.findViewById(R.id.tv_field_name);
                mTvOrderFieldName.setText(mHVVenueOrderFieldBean.getFieldName());
                int statusTextColor=OrderManger.showRefundStatus(mBacking, gymState);//退款中
                mTvOrderWeek.setText(DateUtil.getWeek(mHVVenueOrderFieldBean.getStartTime()));
                mTvOrderWeek.setTextColor(getResources().getColor(statusTextColor));
                mTvOrderDate.setText(DateUtil.stampToDate(mHVVenueOrderFieldBean.getStartTime()));
                mTvOrderDate.setTextColor(getResources().getColor(statusTextColor));
                mTvOrderTime.setText(DateUtil.getHourAndMin(mHVVenueOrderFieldBean.getStartTime()) + "-" + DateUtil.getHourAndMin(mHVVenueOrderFieldBean.getEndTime()));
                mTvOrderTime.setTextColor(getResources().getColor(statusTextColor));
                mTvOrderSinglePrice.setText(DecimalUtils.setPriceStyle(mContext,mHVVenueOrderFieldBean.getPrice(),R.dimen.price_text_size_15,R.dimen.price_text_size_13,true));
                mTvOrderSinglePrice.setTextColor(getResources().getColor(statusTextColor));
                mLlOrderDetailAdd.addView(mOrderChildView);

            }
            changePrice(ihaveCard);//改变总价

        } else if (PRODUCT == orderType) {//课程
            if (StringUtils.isNull(orderProduct)) {
                return;
            }
            int productState = orderProduct.getOrderState().value;
            View mProductOrderView = LayoutInflater.from(mContext).inflate(R.layout.order_detail_product, null, false);
            TextView mTvProductName = (TextView) mProductOrderView.findViewById(R.id.tv_product_name);//产品名称
            TextView mTvProductNum = (TextView) mProductOrderView.findViewById(R.id.tv_product_num);//购买数量
            TextView mTvProductPrice = (TextView) mProductOrderView.findViewById(R.id.tv_product_price);//产品单价
            TextView mTvProductCarDis = (TextView) mProductOrderView.findViewById(R.id.tv_card_discout);//减
            TextView mTvCardName = (TextView) mProductOrderView.findViewById(R.id.tv_card_name);//卡卷名
            ImageView mIvBacking = (ImageView) mProductOrderView.findViewById(R.id.iv_baking);//退款中
                mTvProductCarDis.setVisibility(View.GONE);
                mTvCardName.setVisibility(View.GONE);
            boolean isRefunding = OrderManger.isRefunding(productState);
            OrderManger.showRefundStatus(mIvBacking, productState);//退款的状态显示
            double mSinglePrice = orderProduct.getPrice();
            int num = orderProduct.getNumber();
            mTvProductName.setText(orderProduct.getProductTypeName());
            mTvProductNum.setText("x" + orderProduct.getNumber());
            DecimalUtils.setPriceText(mContext, DecimalUtils.doubleToIntOrD(mSinglePrice), mTvProductPrice, Constants.PRICE_SIZE_THIRTEEN, Constants.YUAN_SIZE_TEN);
            mLlOrderDetailAdd.addView(mProductOrderView);
            mTvProjectName.setText(orderProduct.getProductName());
            changePrice(ihaveCard);//改变总价
        }
        if (isPayAndWithCard) {//支付并且有用了卡卷 实际付款 实付=总额-优惠金额
            mTvDetailActualPrice.setText(DecimalUtils.setPriceStyle(mContext,mAllPrice - discount,R.dimen.price_text_size_15,R.dimen.price_text_size_13,true));
        } else {//没有用卡卷或者没有支付 就使用总额
            mTvDetailActualPrice.setText(DecimalUtils.setPriceStyle(mContext,mAllPrice,R.dimen.price_text_size_15,R.dimen.price_text_size_13,true));
        }
        mTvOrderPrice.setText(DecimalUtils.setPriceStyle(mContext,mAllPrice,R.dimen.price_text_size_15,R.dimen.price_text_size_13,true));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.ll_true_pay)
    public void onClick() {//确认支付
        chosePayWay();
    }
    @OnClick(R.id.ll_revert_rule)
    public void onRevertClick() {//退款规则
        goRevertDetail();
    }

    @OnClick(R.id.ll_forward)
    public void goForward(){//立即前往
        if(null==mForwardDetail){
            return;
        }
        if(null==mBannerIntentManger){
            mBannerIntentManger=new BannerIntentManger(mContext);
        }
        OrderManger.goForwardClick(mForwardDetail,mBannerIntentManger);
    }

    /**
     * 邀请有礼点击
     */
    @OnClick(R.id.tv_invitation)
    public void onClickInvitation(){//邀请有礼
        boolean isShareActivty=StateUtils.isShareActivity(mHVShareActivityBean);
        if(!isShareActivty){
            ToastUtil.showToast(mContext,"该活动已下架");
            return;
        }
        StateUtils.goWebView((BaseActivity) mContext,null,mHVShareActivityBean.getUrl());
    }

    public void goRevertDetail(){
        if(!isCanGoRevertDetail){//是否可点击
            return;
        }
        Bundle mBundle = new Bundle();
        mBundle.putBoolean(Constants.GO_RULE_DETAIL,true);
        mBundle.putString(Constants.WEBVIEW_TITLE,"退款详情");
        mBundle.putString(Constants.WEBVIEW_URL, Cons.URL_REVERT_RULE);
        mBundle.putSerializable(Constants.WEBVIEW_CONFIGS_LIST,mRefundConfigs);
        startActivity(WebViewActivity.class,mBundle,false);

    }

    /**
     * 选择支付的方式
     */
    private void chosePayWay() {
        PaymentDialog paymentDialog = new PaymentDialog(mContext, R.style.BottomToTopAnim, DecimalUtils.doubleToIntOrD(discountedPrice));
        paymentDialog.setPayWay(isZfbPay);
        paymentDialog.setPayListener(new PaymentDialog.OnPayListener() {
            @Override
            public void toPay(View v, int payWay) {
                if(payWay==Constants.ZFB_PAY){//支付宝支付
                    isZfbPay=true;
                }else{
                    isZfbPay=false;
                }
                doSign();
            }
        });

        paymentDialog.show();
    }

    /**
     * 跳到场馆详情
     */
    @OnClick(R.id.tv_order_gym_name)
    public void go_gym_detail(){
        if(mNopay&&isConfirmOrder){//确认订单页面取消跳转
            return;
        }
        if(StringUtils.isNull(mGymId)||StringUtils.isNull(mHVMyOrderInfoBean)){//场馆ID为Null就return
            return;
        }
        boolean isGymOnline=mHVMyOrderInfoBean.getVenueState();//场馆是否上架
        if (isGymOnline) {
            Intent mIntent = new Intent(this, GymDetailActivity.class);
            mIntent.putExtra(Constants.FLAG_INTENT_VENUEID, mGymId);
            startActivity(mIntent);
        }else{
            ToastUtil.showToast(mContext,"该场馆已下架");
        }
    }

    /**
     * 签名
     */
    private void doSign() {
        if(isZfbPay){
            doZFBSign();
        }else{
            doWXSign();
        }

    }

    /**
     * 微信签名
     */

    private void doWXSign() {
        if(!mIWXAPI.isWXAppInstalled()){
            ToastUtil.showToast(mContext,"请先安装微信客服端");
            return;
        }
        loadingView.show();
        IPayService.getSign(this, mOrderId, Enum.EnumPayWay.Wechatpay, isProduct ? Enum.EnumItemType.Product : Enum.EnumItemType.Field, false, null,false, new ObjectCallback<HVSignBean>() {
            @Override
            public void onSuccess(HVSignBean response, String message) {
                dialogDis();
                if(null!=response){
                    appid=response.getAppid();
                    partnerid=response.getPartnerid();
                    prepayid=response.getPrepayid();
                    packageStr=response.getPackageStr();
                    noncestr=response.getNoncestr();
                    timestamp=response.getTimestamp().toString();
                    sign=response.getSign();
                    doWeiXinPay();
                }
            }

            @Override
            public void onErrorT(int code, HVSignBean response, String errorMessage) {
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * 支付宝签名
     */

    private void doZFBSign() {
        loadingView.show();
        IPayService.sign(this, mOrderId, Enum.EnumPayWay.Alipay, isProduct ? Enum.EnumItemType.Product : Enum.EnumItemType.Field, false, null,false, new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response, String message) {
                dialogDis();
                if (!StringUtils.isNull(response)) {
                    payInfo = response;
                    doPay();
                }
            }

            @Override
            public void onErrorT(int code, String response, String errorMessage) {
                ToastUtil.showToast(mContext, errorMessage);
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * 支付
     */

    private void doPay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderDetailActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 订单详情设置返回键的监听事件
     * 当时从预订场地进入 返回就取消订单
     */
    private void setOrderBack() {
        View mBack = mTitleManager.setBack();
        if (mBack != null) {
            mBack.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (isConfirmOrder && mNopay) {//如果是确认订单返回弹框 确定取消
                    doOrderBack(false);
                } else {
                    onBackPressed();
                }
                break;
            case R.id.tv_right://右边的点击事件
                if (mIsPay) {//是否已经支付
                    if (!isProduct) {//场馆的退款
                        ArrayList<HVVenueOrderFieldBean> mHVVenueOrderFieldBeans = getCanRefundList(orderField);
                        doShowGymRefundDialog(mHVVenueOrderFieldBeans);
                    } else {//产品的退款
                        doSHowProductRfDialog();
                    }
                } else {
                    doOrderBack(true);
                }

                break;
            case R.id.rl_code://我的码
                //条形码点击次数
                if(isUsed){
                    ToastUtil.showToast(mContext,"您已使用该条码");
                    return;
                }
                StatisticsManager.onEvent(mContext, StatisticsManager.OrderDetail_Code);
                Bundle mBundle = new Bundle();
                mBundle.putString(Constants.FALG_INTENT_BARCODE, mBarCode);
                startActivity(QRCodeActivity.class, mBundle, false);
                break;
        }
    }

    /**
     * @param orderField 子订单列表
     * @return 可退款的列表
     */

    private ArrayList<HVVenueOrderFieldBean> getCanRefundList(ArrayList<HVVenueOrderFieldBean> orderField) {
        ArrayList<HVVenueOrderFieldBean> mHVVenueOrderFieldBeans = new ArrayList<>();
        for (HVVenueOrderFieldBean mHVVenueOrderFieldBean : orderField) {
            boolean isPayed = OrderManger.isCanRefund(mHVVenueOrderFieldBean.getOrderState().value);//已经付款状态
            int mNowTimes=DateUtil.getCurTimeS();
            double mRevertMoney=mRevertManger.doRevertSingleField(mHVVenueOrderFieldBean,mNowTimes);//可退款的金额 不为－1则为可退款
            if (isPayed&&mRevertMoney!=-1&&mRevertMoney!=0.0) {//已经付款的状态
                mHVVenueOrderFieldBeans.add(mHVVenueOrderFieldBean);
            }
        }
        return mHVVenueOrderFieldBeans;
    }

    /**
     * 产品的退款
     */

    private void doSHowProductRfDialog() {
        final ComDialog dialog = CommonDialogUtils.dialog(OrderDetailActivity.this,getSupportFragmentManager(),getString(R.string.str_order_remind),getString(R.string.str_order_refund), getResources().getString(R.string.submit), getResources().getString(R.string.cancel));
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ArrayList<String> mOrderIds = null;
                boolean isGymWithCard = !isProduct && isPayWithCar;//场馆使用了优惠劵
                if (isGymWithCard) {
                    mOrderIds = new ArrayList<>();//存放子订单Id的集合
                    for (HVVenueOrderFieldBean mHVVenueOrderFieldBean : orderField) {
                        String mOrderId = mHVVenueOrderFieldBean.getFieldOrderId();//子订单Id
                        mOrderIds.add(mOrderId);
                    }
                }
                applyRefund(isProduct, isPayWithCar, mOrderIds);
            }
        });
        dialog.setCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
    }

    /**
     * 弹出退款框
     *
     * @param mHVVenueOrderFieldBeans 可退款的子订单列表
     */
    private void doShowGymRefundDialog(ArrayList<HVVenueOrderFieldBean> mHVVenueOrderFieldBeans) {
        if (StringUtils.isNull(mHVVenueOrderFieldBeans)&&!isPayWithCar) {
            ToastUtil.showToast(mContext, "已无可退款的项目");
            return;
        }
        if (null == mRefundDia) {
            mRefundDia = new RefundDialog(mContext, R.style.BottomToTopAnim, mHandler);
        }
        mRefundDia.setPayWithCard(isPayWithCar);
        if(isPayWithCar){
            mRefundDia.setPrcieData(discountedPrice,discount,mAllPrice);
            double mRevertMonery=mRevertManger.doRevertAllChildOrders(orderField,discountedPrice,DateUtil.getCurTimeS());
            mRefundDia.setPayWithCardRevertMonery(mRevertMonery);

        }
        mRefundDia.show();
        mRefundDia.setOrderField(mHVVenueOrderFieldBeans);//必须在show后面set 因为show之后dialog才加载布局
    }

    /**
     * 返回弹出框或者取消弹出框
     * @param isCancel  是否取消操作
     */

    private void doOrderBack(boolean isCancel) {
        String mStrDialogContent=isCancel?getString(R.string.order_do_cancel):getString(R.string.order_back_remind);
        final ComDialog dialog = CommonDialogUtils.dialog(OrderDetailActivity.this,getSupportFragmentManager(),getString(R.string.str_order_remind), mStrDialogContent, "取消订单", "保留订单");
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                loadingView.show();
                doCancelVenueOrder();
            }
        });
        dialog.setCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                    onBackPressed();
            }
        });
    }

    /**
     * 取消订单
     * 成功返回场馆详情,关闭订座页面
     * 订单Id
     */

    private void doCancelVenueOrder() {
        IOrderService.cancelOrder(this, isProduct ? Enum.EnumCollect.Product : Enum.EnumCollect.Venue, mOrderId, false, new ObjectCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean response, String message) {
                dialogDis();
                boolean isSuccess = response;
                if (isSuccess) {
                    ToastUtil.showToast(mContext, message);
                    if (isFromProduct) {//如果不是产品就跳会场馆详情
                        onBackPressed();
                    } else if (isFromMyOrder) {
                        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_REFRESH_MY_ORDER, null));
                        onBackPressed();
                    } else
//                        startActivity(GymDetailActivity.class, true);
                        onBackPressed();

                }
            }

            @Override
            public void onErrorT(int code, Boolean response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isConfirmOrder && mNopay) {
                doOrderBack(false);
            } else
                onBackPressed();
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    @Subscribe
    public void comeFromMyCard(UiEvent mUiEvent) {
        if (EventConstant.FLAG_COME_BACK_CONFIRM.equals(mUiEvent.getKey())) {//从我的优惠券页面返回
            mHVCardBean = (HVCardBean) mUiEvent.getObject();
            boolean isNu=StringUtils.isNull(mHVCardBean);
            Logger.e("isNll="+isNu);
            updateOrderCouponInfo(mHVCardBean);

        } else if (EventConstant.FLAG_SEAT_REFUND.equals(mUiEvent.getKey())) {//订座退款
            List<HVVenueOrderFieldBean> mSelectedRefund = (List<HVVenueOrderFieldBean>) mUiEvent.getObject();
            ArrayList<String> mOrderIds = new ArrayList<>();//存放子订单Id的集合
            for (HVVenueOrderFieldBean mHVVenueOrderFieldBean : mSelectedRefund) {
                String mOrderId = mHVVenueOrderFieldBean.getFieldOrderId();//子订单Id
                mOrderIds.add(mOrderId);
            }
            applyRefund(false, isPayWithCar, mOrderIds);
        }else if(EventConstant.FLAG_WX_PAY_SUCCESS.equals(mUiEvent.getKey())){//微信支付成功
            tradeQuery();

        }else if(EventConstant.FLAG_WX_PAY_FAIL.equals(mUiEvent.getKey())){//微信支付失败
            doPayFail();
        }
    }

   /**
     * @param isHaveCardBean 当前是否使用过卡卷
     */

    private void changePrice(boolean isHaveCardBean) {
        if (isHaveCardBean) {
//            mTvConfirmDiscount.setText("-" + DecimalUtils.doubleToIntOrD(discount));
            mTvConfirmDiscount.setText(new SpannableStringBuilder("-").append(DecimalUtils.setPriceStyle(mContext,discount,R.dimen.price_text_size_15,R.dimen.price_text_size_13,true)));
            discountedPrice = mAllPrice - discount;

        } else {
            mTvConfirmDiscount.setText("");
            discountedPrice = discountedPrice + discount;//取消卡卷后将加回去
        }
//        setTextView(DecimalUtils.doubleToIntOrD(discountedPrice), mTvActualPrice, Constants.PRICE_ACTUAL_SIZE, Constants.YUAN_SIZE);
        mTvActualPrice.setText(new SpannableStringBuilder("实际支付：").append(DecimalUtils.setPriceStyle(mContext,discountedPrice,R.dimen.price_text_size_21,R.dimen.price_text_size_18,true)));
    }

    /**
     * 去我的卡卷
     */

    @OnClick(rl_card)
    public void goMyCard() {
        //订单详情选择优惠券点击次数
        if(!mNopay){//只有在未支付的情况下才能点击
            return;
        }
        StatisticsManager.onEvent(mContext, StatisticsManager.OrderDetail_Card);

        Bundle mBundle = new Bundle();
        mBundle.putString(Constants.FLAG_GO_MYCARD, Constants.FLAG_GO_MYCARD);
        mBundle.putSerializable(Constants.FALG_INTENT_ORDER_DETAIL, mHVMyOrderInfoBean);
        if(!StringUtils.isNull(mSelctedCouponId)){
            mBundle.putInt(Constants.COUPONID, mSelctedCouponId);//我的卡卷bean
        }
        mBundle.putSerializable(Constants.S_AVAILABLE_COUPON_LIST,mAvailableCouponList);
//        startActivity(MyCouponActivity.class, mBundle, false);
        startActivity(MyCouponActivityNew.class, mBundle, false);
    }

    /**
     * @param isProduct       是否是产品退款
     * @param isPayWithCar    是否是用我的卡卷支付
     * @param itemOrderIdList 子订单退款的Id
     */

    public void applyRefund(final boolean isProduct, boolean isPayWithCar, ArrayList<String> itemOrderIdList) {
        loadingView.show();
        double mTempPrice=isProduct?discountedPrice:mRefundDia.price;
        mRefundAmount=(int)(mTempPrice*100);
        IPayService.applyRefund(this, mOrderId, isProduct ? Enum.EnumRefundType.Product : isPayWithCar ? Enum.EnumRefundType.Field : Enum.EnumRefundType.Subfield, itemOrderIdList, mRefundAmount,false, new ObjectCallback<Object>() {
            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }

            @Override
            public void onSuccess(Object response, String message) {
                ToastUtil.showToast(mContext, message);
                if (!isProduct) {//场地退款
                    if (null != mRefundDia) {
                        mRefundDia.setPriceToO();//场地退款成功将
                    }
                }
                dialogDis();
                getVenueOrderInfo();
                if(null!=mRefundDia){
                    mRefundDia.initRevertDis();//初始化退款扣减
                }

            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);
            }
        });
    }

    /**
     * 更新优惠劵信息
     */
    public void updateOrderCouponInfo(HVCardBean mHvCardBean) {//当mHvCardBean 为null是取消使用
        final boolean isHaveCardBean = !StringUtils.isNull(mHvCardBean);//是否拥有优惠劵
        String mCouponId=null;
        Double money=null;
        Integer couponUserId=null;
        if(isHaveCardBean){
            mCouponId= mHvCardBean.getCouponId();
            money=mCouponManger.getDiscoundPrice(mHvCardBean,mHVMyOrderInfoBean);
            couponUserId=mHvCardBean.couponUserId;
        }
//        String mCouponId = !isHaveCardBean ? null : mHvCardBean.getCouponId();
//        Double money = !isHaveCardBean ? null : mCouponManger.getDiscoundPrice(mHvCardBean,mHVMyOrderInfoBean);//优惠的金额不能大于订单的金额
        loadingView.show();
        IOrderService.updateOrderCouponInfo(this, mOrderId,couponUserId, mCouponId, money, false, new ObjectCallback<HVOrderCardBean>() {
            @Override
            public void onSuccess(HVOrderCardBean response, String message) {
                dialogDis();
                if (null != response) {
                    if (isHaveCardBean) {//绑定卡卷操作
                        discount = response.getCouponMoney();
                        mSelctedCouponId = response.getCouponUserId();
                        String mCardName = response.getCouponName();//卡卷名
                        mTvCardName.setText(mCardName);
                        if (discount >= mAllPrice) {//当前卡卷的减额大于总额 设置为总额为0.01分
                            discount = mAllPrice - 0.01;
                        }
                        changePrice(true);
                    }
                } else {
                    if (!isHaveCardBean) {//取消卡卷操作
                        mTvCardName.setText("");
                        mSelctedCouponId = null;
                        discount=0.0;
                        discountedPrice = mAllPrice;
                        changePrice(false);
                    }
                }
            }

            @Override
            public void onErrorT(int code, HVOrderCardBean response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isBack=false;
        if(ActivityUtils.isBackground(this)){//在后台

        }else {//在前台
            if(isBackGround){//进入后台过
                getVenueOrderInfo();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(ActivityUtils.isBackground(this)){//在后台
            isBackGround=true;
        }else {//在前台
            isBackGround=false;
        }
    }


    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if(Intent.ACTION_SCREEN_ON.equals(action)){//亮屏
                getVenueOrderInfo();
            }else if(Intent.ACTION_SCREEN_OFF.equals(action)){//熄屏
            }
        }
    };

    private void doWeiXinPay(){
        PayReq request = new PayReq();

        request.appId = appid;

        request.partnerId = partnerid;

        request.prepayId= prepayid;

        request.packageValue = packageStr;

        request.nonceStr= noncestr;

        request.timeStamp= timestamp;

        request.sign= sign;

        mIWXAPI.sendReq(request);
    }

}
